package com.guoxin.designpattern.chapter2;

import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author guoxin
 * @date 2019/9/3
 */
public class WaitSet {
    private static final Object LOCK = new Object();

    /**
     * 1、所有的对象都会有一个wait set，用来存放调用了该对象wait方法之后进入block状态的线程
     * 2、线程被notify之后，不一定立即得到执行
     * 3、线程从wait set中被唤醒顺序不一定是FIFO
     *
     * @param args
     */
    public static void main(String[] args) throws InterruptedException {

        IntStream.range(0, 10).forEach(i -> new Thread(String.valueOf(i)) {
            @Override
            public void run() {
                synchronized (LOCK) {
                    try {
                        Optional.of(Thread.currentThread().getName() + " will come to wait set.").ifPresent(System.out::println);
                        LOCK.wait();
                        Optional.of(Thread.currentThread().getName() + " will leave to wait set.").ifPresent(System.out::println);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start());

        TimeUnit.SECONDS.sleep(3);
        IntStream.range(0, 10).forEach(i -> {
            synchronized (LOCK) {
                try {
                    LOCK.notify();
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
